package com.atguigu.wordcount;

import com.atguigu.pojo.WordCount;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink07_WebUIWordCount {



    public static void main(String[] args) {

        // 0. 指定绑定的端口
        //这里是flink的configuration
        Configuration conf = new Configuration();
        conf.setString("rest.addess","localhost");
        conf.setInteger("rest.port",5678);


        //1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.disableOperatorChaining();
        // 设置全局并行度
        env.setParallelism(1) ;

        //2.对接数据
        DataStreamSource<String> ds = env.socketTextStream("hadoop102", 9999);
        //3.转换数据
        SingleOutputStreamOperator<WordCount> flatMapDs = ds.flatMap(
                new FlatMapFunction<String, WordCount>() {
                    @Override
                    public void flatMap(String s, Collector<WordCount> out) throws Exception {
                        String[] words = s.split(" ");
                        for (String word : words) {
                            out.collect(new WordCount(word,1L));
                        }
                    }
                }
        );
        //4.分组求和
        KeyedStream<WordCount ,String> keyBy = flatMapDs.keyBy(
                new KeySelector<WordCount, String>() {
                    @Override
                    public String getKey(WordCount wordCount) throws Exception {
                        return wordCount.getWord();
                    }
                }
        );
        SingleOutputStreamOperator<WordCount> sumDs = keyBy.sum("count");

        sumDs.print();

        //5.执行程序

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
